<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="60%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <div v-loading="loading">
        <PartitionTitle title="基础信息"></PartitionTitle>
        <el-form
          :model="form"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          :disabled="!canEdit"
        >
          <el-form-item label="工位编码" prop="workStationCode">
            <el-input
              type="text"
              v-model="form.workStationCode"
              placeholder="请输入工位编码"
              :disabled="!!form.id"
            ></el-input>
            <el-switch
              v-model="systemNumber"
              active-text="系统编号"
              class="system-num"
              :disabled="!!form.id"
              @change="handleGetCode"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="工位名称" prop="workStationName">
            <el-input
              type="text"
              v-model="form.workStationName"
              placeholder="请输入工位名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属工厂" prop="factoryDeptCode">
            <el-select
              v-model="form.factoryDeptCode"
              placeholder="请选择所属工厂"
              @change="handleFactoryChange"
            >
              <el-option
                v-for="item in factoryList"
                :key="item.factoryDeptCode"
                :label="item.factoryName"
                :value="item.factoryDeptCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属车间" prop="workshopId">
            <el-select
              v-model="form.workshopId"
              placeholder="请选择所属车间"
              @change="handleWorkshopChange"
            >
              <el-option
                v-for="item in workShopList"
                :key="item.workshopId"
                :label="item.workshopName"
                :value="item.workshopId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属产线" prop="lineId">
            <el-select v-model="form.lineId" placeholder="请选择所属产线">
              <el-option
                v-for="item in productionLineList"
                :key="item.lineId"
                :label="item.lineName"
                :value="item.lineId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="每班配置人数" prop="userCntPerGroup">
            <el-input-number
              v-model="form.userCntPerGroup"
              :min="0"
              :step="1"
              step-strictly
            ></el-input-number>
          </el-form-item>
          <el-form-item
            label="工位描述"
            prop="workStationDesc"
            style="width: 100%"
          >
            <el-input
              type="text"
              v-model="form.workStationDesc"
              placeholder="请输入工位描述"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getWorkStation,
  addOrUpdateWorkStation,
} from "@/api/workMgmt/workStation";
import { getNextCodeByModule } from "@/api/common";
import { checkPermi } from "@/utils/permission";
import WorkTree from "@/utils/workTree";
export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      form: {
        id: null,
        workStationCode: null,
        workStationName: null,
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        lineId: null,
        userCntPerGroup: null,
        workStationDesc: null,
        workshopId: null,
      },
      rules: {
        workStationCode: [
          { required: true, message: "请输入工位编码", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            message: "支持字母(A-Z、a-z)、数字(0-9)",
            trigger: "blur",
          },
          { max: 32, message: "32个字符以内", trigger: "blur" },
        ],
        workStationName: [
          { required: true, message: "请输入工位名称", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message: "支持中文、字母(A-Z、a-z)、数字(0-9)和下滑线",
            trigger: "blur",
          },
          { max: 32, message: "32个字符以内", trigger: "blur" },
        ],
        factoryDeptCode: [
          { required: true, message: "请选择所属工厂", trigger: "change" },
        ],
        lineId: [
          { required: true, message: "请选择所属产线", trigger: "change" },
        ],
        userCntPerGroup: [
          { required: true, message: "请输入每班配置人数", trigger: "change" },
        ],
        workshopId: [
          { required: true, message: "请选择所属车间", trigger: "change" },
        ],
      },
      // 工厂列表
      factoryList: [],
      // 车间列表
      workShopList: [],
      // 产线列表
      productionLineList: [],
      saveloading: false,
      systemNumber: false,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return "工位人员详情";
      }
      if (!!this.row) {
        return "编辑工位人员";
      }
      return "新增工位人员";
    },
    rowBranchinnercode() {
      return this.form.factoryDeptId || null;
    },
    canEdit() {
      if (this.disabled == true) {
        return false;
      }
      if (this.row?.id) {
        return checkPermi(["workMgmt:workSection:edit"]);
      }
      return true;
    },
  },
  methods: {
    handleClose() {
      this.saveloading = false;
      this.resetFormData();
    },
    async handleOpen() {
      // 工厂-车间-产线-工序-工位
      this.workTree = new WorkTree();
      await this.workTree.affterLoad();

      this.getDetail();
      this.factoryList = this.workTree.getFactory();
    },
    // 获取详情
    getDetail() {
      if (!this.row?.id) {
        // 默认获取第一个工厂
        const results = this.getOwnFirstLine();
        this.form.factoryDeptCode = results[0]?.factoryDeptCode || "";
        this.form.factoryDeptId = results[0]?.factoryDeptId || "";
        return;
      }
      this.loading = true;
      getWorkStation(this.row.id)
        .then((res) => {
          if (res.code == 200 && res.data) {
            const {
              id,
              workStationCode,
              workStationName,
              factoryDeptId,
              factoryDeptCode,
              lineId,
              userCntPerGroup,
              workStationDesc,
              workshopId,
            } = res.data;
            this.form = {
              id,
              workStationCode,
              workStationName,
              factoryDeptId,
              factoryDeptCode,
              lineId,
              userCntPerGroup,
              workStationDesc,
              workshopId,
            };
            this.$nextTick(() => {
              this.$refs.ruleForm?.clearValidate();
            });
          }
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    handleSubmit() {
      if (!this.canEdit) {
        return;
      }
      this.saveloading = true;
      this.$refs.ruleForm.validate((flag) => {
        if (flag && !this.monthError) {
          const {
            id,
            workStationCode,
            workStationName,
            factoryDeptId,
            lineId,
            userCntPerGroup,
            factoryDeptCode,
            workStationDesc,
            workshopId,
          } = this.form;
          const param = {
            id,
            workStationCode,
            workStationName,
            factoryDeptId,
            factoryDeptCode,
            lineId,
            userCntPerGroup,
            workStationDesc,
            workshopId,
          };
          addOrUpdateWorkStation(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(id ? "修改成功！" : "新增成功！");
                this.$emit("submit-success");
                this.dialogVisible = false;
              }
              this.saveloading = false;
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          this.saveloading = false;
        }
      });
    },
    resetFormData() {
      this.$refs.ruleForm?.resetFields();
      this.form = {
        id: null,
        workStationCode: null,
        workStationName: null,
        factoryDeptId: null,
        lineId: null,
        userCntPerGroup: null,
        factoryDeptCode: null,
        workStationDesc: null,
        // workStationUsers: [],
        workshopId: null,
      };
      this.systemNumber = false;
    },
    handleGetCode(value) {
      if (value == true) {
        getNextCodeByModule("WORK_STATION").then((res) => {
          if (res.code == 200) {
            this.form.workStationCode = res.data || null;
            this.$refs.ruleForm.validateField("workStationCode");
          }
        });
      }
    },
    handleFactoryChange(factoryDeptCode) {
      this.form.workshopId = null;
      this.form.lineId = null;
      this.form.factoryDeptId = this.factoryList.find(
        (ele) => ele.factoryDeptCode == factoryDeptCode
      ).factoryDeptId;
    },
    handleWorkshopChange() {
      this.form.lineId = null;
    },
  },
  watch: {
    "form.factoryDeptCode": {
      handler(newVal) {
        if (newVal) {
          this.workShopList = this.workTree.getWorkshop({
            factoryDeptCode: newVal,
          });
        } else {
          this.workShopList = [];
        }
      },
    },
    "form.workshopId": {
      handler(newVal) {
        if (newVal) {
          this.productionLineList = this.workTree.getProductionLine({
            workshopId: newVal,
          });
        } else {
          this.productionLineList = [];
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
  }
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
    .system-num {
      white-space: nowrap;
      margin-left: 10px;
    }
    .el-date-editor.el-input,
    .el-select,
    .el-cascader,
    .factory-select,
    .el-input-number {
      width: 100%;
    }
  }
}
.tool-bar {
  margin-bottom: 10px;
}
</style>
